import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { Search24 as SearchIcon } from '@carbon/icons-react';
import { withRouter } from 'react-router';
import dayjs from 'dayjs';

import Input from '@kuiper-components/input';
import Button from '@kuiper-components/button';

import DateRange from '../../../../components/DateRange';
import s from './style.module.css';

const earilestTime = dayjs(new Date()).subtract(6, 'months');
function Toolbox({ className, value, onChange }) {
	const [affects, setaffects] = React.useState(value?.affects);

	const dateRange = {
		startTime: value?.startTime,
		endTime: value?.endTime,
	};

	const searchString = Object.entries(value).reduce((str, [key, val], idx) => {
		str += `&${key}=${val}`;
		return str;
	}, '?sort=_ID_DESC');
	const downloadApi = `/api/v1/log-download${searchString}`;

	const handleDateChange = val => {
		onChange({
			...value,
			startTime: val?.startTime || undefined,
			endTime: val?.endTime || undefined,
		});
	};
	const handleAffectsChange = val => {
		setaffects(val);
		if (!val) {
			onChange({ ...value, affects: undefined });
		}
	};

	const handleSearchCommit = () => {
		onChange({ ...value, affects });
	};

	const handleReset = () => {
		onChange({ affects });
	};

	return (
		<div className={cn(className, s.toolbox)}>
			<Input
				onChange={handleAffectsChange}
				className={s.input}
				placeholder="请输入资产地址"
				after={<SearchIcon className={s.icon} onClick={handleSearchCommit} />}
				value={affects}
				onPressEnter={handleSearchCommit}
				type="search"
			/>
			<div className={s.selectContainer}>
				<DateRange
					value={dateRange}
					minDate={earilestTime}
					onChange={handleDateChange}
				/>
				<Button className={s.btn} onClick={handleReset}>
					重置
				</Button>
				<a href={downloadApi}>
					<Button className={s.btn} primary>
						导出
					</Button>
				</a>
			</div>
		</div>
	);
}

Toolbox.propTypes = {
	className: PropTypes.string,
	value: PropTypes.object,
	onChange: PropTypes.func.isRequired,
};
Toolbox.defaultProps = {
	className: '',
};

export default withRouter(Toolbox);
